package com.cloud.easy.im.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.Properties;

/**
 * redis 工具类
 *
 * @author wangjian
 * @version 0.1.0
 * @create 2020年09月21日6:38 下午
 */
public class RedisProvider {

    private static final Logger logger = LoggerFactory.getLogger(RedisProvider.class);

    private static final JedisPool JEDIS_POOL;

    private static Properties properties;

    private static final String PRO_PATH = "redisConfig.properties";
    private static final String AUTH_FLAG = "redis.authFlag";
    private static final String PASSWORD = "redis.password";

    private static boolean authFlag = false;

    private static String password;

    static {
        //读取配置文件
        try {
            readConfigFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 配置连接池
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(20);
        poolConfig.setMinIdle(10);
        poolConfig.setMaxTotal(30);
        poolConfig.setMaxWaitMillis(3000);
        poolConfig.setEvictorShutdownTimeoutMillis(0);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        poolConfig.setTestWhileIdle(true);
        JEDIS_POOL = new JedisPool(properties.getProperty("redis.host"), Integer.parseInt(properties.getProperty("redis.port")));

        //判断是否需要密码验证
        if ("1".equals(properties.getProperty(AUTH_FLAG))) {
            authFlag = true;
            password = properties.getProperty(PASSWORD);
            if (password == null) {
                try {
                    throw new Exception("redis密码没有读取到！");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void readConfigFile() throws IOException {
        InputStream inputStream = RedisProvider.class.getResourceAsStream("/" + PRO_PATH);
        if (Objects.isNull(inputStream)) {
            throw new IOException("读取不到配置文件：" + PRO_PATH);
        }
        properties = new Properties();
        properties.load(inputStream);
        inputStream.close();
    }

    public static Jedis getResource() {
        Jedis jedis = JEDIS_POOL.getResource();
        if (authFlag) {
            jedis.auth(password);
        }
        return jedis;
    }

    public static void close() {
        JEDIS_POOL.close();
    }
}
